package org.oschina.api.manage.illegalchar.service;

import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.oschina.Constants;
import org.oschina.Message;
import org.oschina.Module;
import org.oschina.ResultUtil;
import org.oschina.api.BaseService;
import org.oschina.api.manage.illegalchar.dao.IllegalCharDAO;
import org.oschina.api.manage.illegalchar.model.IllegalChar;
import org.oschina.api.manage.illegalchar.vo.IllegalCharVo;
import org.oschina.bean.Result;
import org.oschina.api.index.service.IndexService;
import org.oschina.security.annotation.Require;
import org.oschina.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class IllegalCharService extends BaseService {

	@Autowired
	private IllegalCharDAO illegalCharDAO;
	@Autowired
	private IndexService indexService;
	
	//特殊字符
	private final String oldStr[]={"\"", "'", "<", ">", "\n", "\t", "\r"};
	private final String newStr[]={"&quot;", "&apos;", "&lt;", "&gt;", "<n>", "<t>", "<n>"};
	
	/**
	 * 返回
	 * @return
	 */
	@Require(authorization=Module.MODULE_10)
	public List<IllegalCharVo> findVo()
	{
		return illegalCharDAO.findVo();
	}
	
	/**
	 * 创建
	 * @param illegalChar
	 * @return
	 */
	@Require(authorization=Module.MODULE_10)
	public Result create(IllegalChar illegalChar)
	{
		illegalChar.setId(_getIndex());
		illegalChar.setCreate_time(DateUtil.now());
		illegalCharDAO.create(illegalChar);
		return ResultUtil.getSuccess(illegalChar);
	}
	 
	/**
	 * 更新
	 * @param illegalChar
	 * @return
	 */
	@Require(authorization=Module.MODULE_10)
	public Result update(IllegalChar illegalChar)
	{
		if(illegalCharDAO.update(illegalChar)==0)
			return ResultUtil.getFailure(Message.ERROR_DATA_ERROR);
		
		return ResultUtil.getSuccess(illegalChar);
	}
	
	/**
	 * 删除
	 * @return
	 */
	@Require(authorization=Module.MODULE_10)
	public Result remove(int id)
	{
		if(illegalCharDAO.remove(id)==0)
			return ResultUtil.getFailure(Message.ERROR_DATA_ERROR);
		
		return ResultUtil.getSuccess(Message.DELETE_SUCCESS);
	}
	
	
	/**
	 * 清除非法字符
	 * @param str
	 * @return
	 */
	public String _clean(String str)
	{
		str=StringUtils.replaceEach(str,oldStr,newStr).trim();
		List<IllegalCharVo> illegalChars=findVo();
		for(IllegalCharVo illegalChar:illegalChars)
			str=StringUtils.replace(str, illegalChar.getSource(), illegalChar.getReplace());
		return str;
	}
	
	private int _getIndex()
	{
		return indexService.getMajorById(Constants.INDEX_ILLEGAL_CHAR);
	}
}